from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QLabel,
                             QLineEdit, QWidget)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import qrcode
from io import BytesIO


class QRDialog(QDialog):
    def __init__(self, parent=None, connection_url=""):
        super().__init__(parent)
        self.connection_url = connection_url
        self.setWindowTitle("手机连接")
        self.setFixedSize(300, 400)
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        # 创建 QR 码图片
        qr_label = QLabel()
        qr_pixmap = self.generate_qr_code()
        qr_label.setPixmap(qr_pixmap)
        qr_label.setAlignment(Qt.AlignCenter)

        # 创建 URL 显示框
        url_input = QLineEdit(self.connection_url)
        url_input.setReadOnly(True)
        url_input.setAlignment(Qt.AlignCenter)

        # 添加到布局
        layout.addWidget(qr_label)
        layout.addWidget(url_input)
        layout.setAlignment(Qt.AlignCenter)

        self.setLayout(layout)

    def generate_qr_code(self):
        # 生成二维码
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(self.connection_url)
        qr.make(fit=True)

        # 转换为 PIL Image
        qr_image = qr.make_image(fill_color="black", back_color="white")

        # 转换为 150x150 的 QPixmap
        buffer = BytesIO()
        qr_image.save(buffer, format='PNG')
        pixmap = QPixmap()
        pixmap.loadFromData(buffer.getvalue())
        return pixmap.scaled(150, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation)
